package com.gali.rabbit.four;

import com.gali.rabbit.utils.RabbitMqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeoutException;

/**
 * @Auther: gali
 * @Date: 2022-08-02 14:46
 * @Description:发布确认模式
 * 单个确认模式--327ms
 * 批量确认模式--124ms
 * 异步确认模式--42ms
 * 使用的时间来比较谁最快
 */
public class ConfirmMessage {
    //批量发消息的个数
    public static final int MESSAGE_COUNT=1000;
    public static void main(String[] args) throws Exception {
        //1.单个确认模式
//        ConfirmMessage.publishMessageIndividually();
        //2.批量确认模式
//        ConfirmMessage.confirmMessageBatch();
        //3.异步确认模式
        ConfirmMessage.publishMessageAsync();
    }

    //单个确认模式
    public static void publishMessageIndividually() throws Exception{
        Channel channel = RabbitMqUtils.getChannel();
        String s = UUID.randomUUID().toString();
        channel.queueDeclare(s,true,false,false,null);//队列的声明
        channel.confirmSelect(); //开启发布确认
        //开始时间
        long begin = System.currentTimeMillis();
        //批量发送
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message="";
            channel.basicPublish("",message,null,message.getBytes());
            //单个消息马上进行确认
            boolean b = channel.waitForConfirms();
            if (b){
                System.out.println("消息发送成功");
            }
        }
        //结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"个单独确认消息，耗时："+(end-begin)+"ms");
    }
    //批量确认模式
    public static void confirmMessageBatch() throws IOException, TimeoutException, InterruptedException {
        Channel channel = RabbitMqUtils.getChannel();
        String s = UUID.randomUUID().toString();
        channel.queueDeclare(s,true,false,false,null);//队列的声明
        channel.confirmSelect(); //开启发布确认
        //开始时间
        long begin = System.currentTimeMillis();
        //批量确认消息的大小
        int batchSize=100;
        //批量发送消息并批量确认
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message=i+"";
            channel.basicPublish("",s,null,message.getBytes());
            //判断达到100消息的时候进行批量确认
            if (i%batchSize==0){
                channel.waitForConfirms();//发布确认
            }
        }
        //结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"个批量确认消息，耗时："+(end-begin)+"ms");
    }
    //异步确认模式
    public static void publishMessageAsync() throws Exception{
        Channel channel = RabbitMqUtils.getChannel();
        String s = UUID.randomUUID().toString();
        channel.queueDeclare(s,true,false,false,null);//队列的声明
        channel.confirmSelect(); //开启发布确认
        //线程安全有序的hash表，适用于高并发的情况下
        //1.轻松的将序号与消息关联  2.轻松的批量删除条数 只要给到序号
        //3.支持高并发
        ConcurrentSkipListMap<Long,String> outstandingConfirms=new ConcurrentSkipListMap<>();
        //监听成功 1.消息的标识 2.是否批量确认
        ConfirmCallback ackCallback=(deliveryTag,multiple)->{
            if (multiple){
                ConcurrentNavigableMap<Long, String> confirmed = outstandingConfirms.headMap(deliveryTag);
                confirmed.clear();
            }else{
                outstandingConfirms.remove(deliveryTag);
            }
            System.out.println("消息发送成功:"+deliveryTag);
        };
        //监听失败
        ConfirmCallback nackCallback=(deliveryTag,multiple)->{
            String message = outstandingConfirms.get(deliveryTag);
            System.out.println("消息发送失败:"+deliveryTag+"未确认的消息是："+message);
        };
        //准备消息的监听器，监听哪些消息成功/不成功
        channel.addConfirmListener(ackCallback,nackCallback);
        //开始时间
        long begin = System.currentTimeMillis();
        //批量发送
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message="消息"+i;
            channel.basicPublish("",s,null,message.getBytes());//发布消息
            //记录所有发送的消息 消息的总和
            outstandingConfirms.put(channel.getNextPublishSeqNo(),message);
        }
        //结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"个异步确认消息，耗时："+(end-begin)+"ms");
    }
}
